package com.dmall.play.interview.chapter07;

import java.util.ArrayList;
import java.util.List;

public class Leetcode129V1 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            return "TreeNode {" +
                    "val=" + val +
                    '}';
        }
    }

    public int sumNumbers(TreeNode root) {
        List<String> paths = new ArrayList<>();
        constructPath(root, "", paths);
        int sum = 0;
        for (String path : paths) {
            sum += Integer.parseInt(path);
        }
        return sum;
    }

    private void constructPath(TreeNode node, String path, List<String> paths) {
        if (node != null) {
            StringBuilder sb = new StringBuilder(path);
            sb.append(node.val);
            if (node.left == null && node.right == null) {
                paths.add(sb.toString());
            } else {
                constructPath(node.left, sb.toString(), paths);
                constructPath(node.right, sb.toString(), paths);
            }
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.right = new TreeNode(5);
        root.right = new TreeNode(3);

        Leetcode129V1 leetcode129 = new Leetcode129V1();
        List<String> paths = new ArrayList<>();
        leetcode129.constructPath(root, "", paths);
        System.out.println(paths);
        int sum = leetcode129.sumNumbers(root);
        System.out.println(sum);
    }
}
